#!/usr/bin/env python
# -*- coding: utf-8 -*-

import threading
import commands
import time
import os, sys
import logging



def daemon_init(stdin='/dev/null',stdout='/dev/null',stderr='/dev/null'):
	try:
		pid = os.fork()
		if(pid > 0):
			sys.exit(0)
	except OSError , e:
		sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) ) ;
		sys.exit(1)

	os.chdir("/") 
	os.umask(0)
	os.setsid()

	try:
		pid = os.fork()
		if(pid > 0):
			sys.exit(0)
	except OSError , e:
		sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) ) ;
		sys.exit(1)

	for f in sys.stdout, sys.stderr: f.flush()  
	si = open(stdin, 'r')  
	so = open(stdout, 'a+')  
	se = open(stderr, 'a+', 0)  
	os.dup2(si.fileno(), sys.stdin.fileno())    #dup2函数原子化关闭和复制文件描述符  
	os.dup2(so.fileno(), sys.stdout.fileno())  
	os.dup2(se.fileno(), sys.stderr.fileno())

if __name__ == '__main__':      
	
	daemon_init()
	BMC_LOGGER = logging.getLogger(__name__)
	BMC_LOGGER.setLevel(20)
	fh = logging.FileHandler('/root/jpython/tools/aemon_test.log','a')
	fh.setFormatter(logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"))
	BMC_LOGGER.addHandler(fh)

	#确认是否有python daemon.py 运行中
	#root       3199      1  0 12:26 ?        00:00:00 python ./daemon.py
        cmd='ps -ef | grep daemon.py'
	status, output = commands.getstatusoutput(cmd)
	BMC_LOGGER.info(output)
	find_daemon_t = 0
	for lint_t in output.split('\n'):
		if(lint_t.find('python') > 0 and lint_t.find('start')>0 and lint_t.find('ctrl')>0):
			find_daemon_t = find_daemon_t+1
	if(find_daemon_t > 1):
		BMC_LOGGER.info("damon running, number[%d],exit(0)",find_daemon_t)
		sys.exit(0)
	while(True):
		time.sleep(10);
		BMC_LOGGER.info("run once")
